package com.leyou.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {


    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //验证码 存入redis中的key值
    private static final String KEY_PREFIX = "user:verify:code:phone:";


    /**
     * 查询数据是否存在
     * @param data 要校验的数据
     * @param type 数据的类型，1：用户名，2：手机号
     * @return boolean
     */
    @Override
    public Boolean queryInfoExist(String data, Integer type) {
        //请求数据只能是1、2
        if (type != 1 && type != 2){
            throw new LyException(500,"请求参数有误！");
        }
        //返回结果
        //select count（*） from tb_user where (type = 1 and username = data) or (type = 2 and phone = data )
        Integer count = query().eq(type == 1, "username", data)
                .eq(type == 2, "phone", data).count();

        return count == 1;
    }

    /**
     * 通过用户名、密码查询查询用户
     * @param username 用户名
     * @param password 密码
     * @return userDTO
     */
    @Override
    public UserDTO queryUserByUserNameAndPassword(String username, String password) {

        // 1.根据用户名查询
        //User user = userMapper.queryUserByUserName(username);
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        // 2.判断是否存在
        if (user == null) {
            // 用户名错误
            throw new LyException(400, "用户名或密码错误");
        }

        // 3.校验密码
        if(!passwordEncoder.matches(password, user.getPassword())){
            // 密码错误
            throw new LyException(400, "用户名或密码错误");
        }
        // 4.转换DTO
        return new UserDTO(user);
    }

    /**
     * 发送验证码
     * @param phone 电话号码
     * @return void
     */

    @Override
    public void sendMessageCode(String phone) {
        //校验手机号码
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400,"手机号码格式有误！");
        }
        //生成随机验证码
        String code = RandomStringUtils.randomNumeric(6);
        //将验证码保存到redis中
        stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone , code , 300 , TimeUnit.MINUTES);
        //发送验证码  1.交换机 2.key 3.数据
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,map);
    }

    /**
     * 注册用户
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     */
    @Override
    @Transactional
    public void registerUser(User user, String code) {
        //1.校验验证码
        String redisCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        if (!StringUtils.equals(code, redisCode)) {
            throw new LyException(400, "验证码错误");
        }

        //2.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        //3.写入数据库
        this.save(user);
    }

}
